package com.csrcb.tools;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Map;
import java.util.Properties;

/**
 * @Classname EmailUtil
 * @Description 邮箱发送的工具类
 * @Date 2020/12/18 14:37
 * @Created by gangye
 */
public class EmailUtil {

    /**
     * 调用qq发送邮件
     * @param paranMap
     * @throws AddressException
     * @throws MessagingException
     */
    public static void sendQQEmail(QqEmailObject paranMap) throws AddressException, MessagingException {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
        //得到回话对象
        Session session = Session.getInstance(properties);
        //获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress(paranMap.getSendAddress()));
        // 设置收件人邮箱地址,多个收件人之间使用
        // message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com")});
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(paranMap.getAcceptAddress()));//一个收件人
        // 设置邮件标题
        message.setSubject(paranMap.getTitle());
        // 设置邮件内容
        message.setText(paranMap.getEmailContent());
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect(paranMap.getSendAddress(), paranMap.getToken());// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     * 使用网易的163邮箱
     * @param netEasyEmailOnject
     */
    public static void sendNetEasyEmail(NetEasyEmailOnject netEasyEmailOnject) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.163.com");//设置发送邮件的邮件服务器的属性（这里使用网易的smtp服务器）
        props.put("mail.smtp.auth", "true");  //需要经过授权，也就是有户名和密码的校验，这样才能通过验证（一定要有这一条）
        Session session = Session.getDefaultInstance(props);//用props对象构建一个session
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);//用session为参数定义消息对象
        try {
            message.setFrom(new InternetAddress(netEasyEmailOnject.getSendAddress()));// 加载发件人地址
            InternetAddress[] sendTo = new InternetAddress[netEasyEmailOnject.getAcceptsAddress().length]; // 加载收件人地址
            for (int i = 0; i < netEasyEmailOnject.getAcceptsAddress().length; i++) {
                sendTo[i] = new InternetAddress(netEasyEmailOnject.getAcceptsAddress()[i]);
            }
            message.addRecipients(Message.RecipientType.TO,sendTo);
            message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(netEasyEmailOnject.getSendAddress()));//设置在发送给收信人之前给自己（发送方）抄送一份，不然会被当成垃圾邮件，报554错
            message.setSubject(netEasyEmailOnject.getTitle());//加载标题
            Multipart multipart = new MimeMultipart();//向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            BodyPart contentPart = new MimeBodyPart();//设置邮件的文本内容
            contentPart.setText(netEasyEmailOnject.getNetEastContent());
            multipart.addBodyPart(contentPart);
            if(netEasyEmailOnject.getAffixAddress()!=null && !netEasyEmailOnject.getAffixAddress().isEmpty()){//添加附件
                BodyPart messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(netEasyEmailOnject.getAffixAddress());
                messageBodyPart.setDataHandler(new DataHandler(source));//添加附件的内容
                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();//添加附件的标题
                messageBodyPart.setFileName("=?GBK?B?"+ enc.encode(netEasyEmailOnject.getAffixName().getBytes()) + "?=");
                multipart.addBodyPart(messageBodyPart);
            }
            message.setContent(multipart);//将multipart对象放到message中
            message.saveChanges(); //保存邮件
            Transport transport = session.getTransport("smtp");//发送邮件
            transport.connect("smtp.163.com", netEasyEmailOnject.getUser(), netEasyEmailOnject.getToken());//连接服务器的邮箱
            transport.sendMessage(message, message.getAllRecipients());//把邮件发送出去
            transport.close();//关闭连接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
